from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relation, backref, deferred, mapper
from sqlalchemy.types import BigInteger, Integer, String, DateTime
from sqlalchemy.dialects.mysql import ENUM

from fidoweb.model.meta import Base
from fidoweb.model.map import School

"""
Rules
	1. Tables and Inner relations are sorted in alphabet order, and Inner relations are defined after Tables
	2. About relations:
		For m-m relations: 'relation' defined in the first element of the relation
		For o-m(m-o) relations: 'relation' defined in the element of 'm' side
"""

"""
Tables
	City
	Country
	State
"""

"""
Inner relations
	City(state) m-o State(cities)
	Country(states) o-m State(country)
"""

"""
Outer relations
	City(schools) o-m School(city)
"""

City_t = Table('cities', Base.metadata,
	Column('id', Integer, primary_key = True),
	Column('name', String(64), unique = True),
	Column('state_id', Integer, ForeignKey('states.id')),
)

Country_t = Table('countries', Base.metadata, 
	Column('id', Integer, primary_key = True),
	Column('name', String(64), unique = True),
)

State_t = Table('states', Base.metadata, 
	Column('id', Integer, primary_key = True),
	Column('name', String(64), unique = True),
	Column('country_id', Integer, ForeignKey('countries.id')),
)

class City(object) :
	def __init__(self, name, state_id) :
		self.name = name
		self.state_id = state_id

class Country(object) :
	def __init__(self, name) :
		self.name = name

class State(object) :
	def __init__(self, name, country_id) :
		self.name = name
		self.country_id = country_id

mapper(City, City_t, properties = {
	'id' : City_t.c.id,
	'name' : City_t.c.name,
	'state_id' : City_t.c.state_id,
	'schools' : relation(School, backref = 'city'),
})

mapper(Country, Country_t, properties = {
	'id' : Country_t.c.id,
	'name' : Country_t.c.name,
	'states' : relation(State, backref = 'country'),
})

mapper(State, State_t, properties = {
	'id' : State_t.c.id,
	'name' : State_t.c.name,
	'country_id' : State_t.c.country_id,
	'cities' : relation(City, backref = 'state'),
})